﻿using System;
using System.Threading.Tasks;
using Kele.Activity.Core;
using Kele.Activity.Models;
using Kele.Core.Extensions;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Kele.Core.Http;
using Kele.Activity.Web.Controllers.V1;

namespace Kele.Activity.Web.Controllers.v1
{
    [Route("api/merchant")]
    public class MerchantController : SiteApiController
    {
        [Route("info")]
        [HttpGet]
        public async Task<IActionResult> GetInfo()
        {
            var r = await AppService.Merchant.GetInfoAsync(MerchantId);
            return OkResult(r);
        }

        [Route("update/person")]
        [HttpPost]
        public async Task<IActionResult> UpdatePerson()
        {
            var json = await Request.GetRawBodyStringAsync();
            var merchant = JsonConvert.DeserializeObject<Merchant>(json);
            if (merchant.id != MerchantId) return ErrorResult("你们有权限");
            await AppService.Merchant.UpdatePersonInfoAsync(merchant);
            return OkResult();
        }

        #region store

        [Route("store/list")]
        [HttpGet]
        public async Task<IActionResult> GetStoreList(int take = 0, int skip = 0)
        {
            var ret = await AppService.Merchant.GetStoreList(MerchantId, skip, take);
            return OkResult(ret);
        }

        [Route("store/update")]
        [HttpPost]
        public async Task<IActionResult> UpdateStore()
        {
            var json = await Request.GetRawBodyStringAsync();
            var store = JsonConvert.DeserializeObject<MerchantStore>(json);
            await AppService.Merchant.UpdateStore(MerchantId, store);
            return OkResult();
        }

        [Route("store/delete")]
        [HttpPost]
        public async Task<IActionResult> DeleteStore()
        {
            var id = Request.Params("id");
            if (string.IsNullOrWhiteSpace(id)) return ErrorResult("id is required");
            int.TryParse(id, out var storeId);
            await AppService.Merchant.DeleteStore(MerchantId, storeId);
            return OkResult();
        }

        #endregion store
    }
}